#include <iostream>
#include <cerrno>
#include <cstring>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include "Thread.hpp"
#include "InetAddr.hpp"

// 使用手册
void Usage(std::string proc)
{
    std::cout << "Usage : \n\t" << proc << " server_ip server_port\n" << std::endl;
}

struct ThreadData
{
    ThreadData(int sockfd, InetAddr addr)
        :_sockfd(sockfd), _addr(addr)
    {}

    ~ThreadData()
    {}

    int _sockfd;
    InetAddr _addr;
};

void ReceiverRoutine(ThreadData &data)
{
    char buffer[4096];
    while(true)
    {
        // 收消息
        struct sockaddr_in temp;
        socklen_t len = sizeof(temp);
        ssize_t n = recvfrom(data._sockfd, buffer, sizeof(buffer)-1, 0, (struct sockaddr*)&temp, &len);   // 最后两个参数一般建议都是要填的（传空指针会有坑）
        if(n > 0)
        {
            buffer[n] = 0;
            std::cerr << buffer << std::endl;   // 错误流打印，方便测试
        }
        else break;
    }
}

void SenderRoutine(ThreadData &data)
{
    struct sockaddr_in addr = data._addr.GetAddr();
    while(true)
    {
        // 我们要发的数据
        std::string inbuffer;
        std::cout << "Please Enter# ";
        std::getline(std::cin, inbuffer);
        // 给server端发消息
        ssize_t n = sendto(data._sockfd, inbuffer.c_str(), inbuffer.size(), 0, (struct sockaddr*)&addr, sizeof(addr));
        if(n <= 0)
        {
            std::cout << "send error" << std::endl;
        }
    }
}

// ./udp_client server_ip server_port
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    std::string serverip = argv[1];             // 服务端ip
    uint16_t serverport = std::stoi(argv[2]);   // 服务端port

    // 1. 创建套接字
    int sockfd = socket(AF_INET, SOCK_DGRAM, 0);
    if(sockfd < 0)
    {
        std::cerr << "socket error: " << strerror(errno) << std::endl;
        return 1;
    }
    std::cout << "create socket success: " << sockfd << std::endl;

    // 2. client要不要进行bind？一定要。但是不需要显示bind，client会在首次发送数据时自动进行bind
    // 为什么？server端的ip和端口号，一定是众所周知的，不可改变的，client需要bind随机端口
    // 为什么？因为client会非常多，不随机绑定端口容易出现端口冲突
    // 2.1 填充server信息
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(serverport);
    server.sin_addr.s_addr = inet_addr(serverip.c_str());

    InetAddr addr(server);
    ThreadData data(sockfd, addr);

    Thread<ThreadData> recevier("receiver", ReceiverRoutine, data);
    Thread<ThreadData> sender("sender", SenderRoutine, data);

    recevier.Start();
    sender.Start();

    recevier.Join();
    sender.Join();

    close(sockfd);
    return 0;
}
